package com.cskaoyan.service;

import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.MarketKeyword;
import com.cskaoyan.bean.po.MarketKeywordExample;
import com.cskaoyan.mapper.MarketKeywordMapper;
import com.cskaoyan.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author wangzhenyu
 * @since 2022/11/21 16:08
 */
@Service
public class KeywordServiceImpl implements KeywordService {
    @Autowired
    MarketKeywordMapper marketKeywordMapper;

    @Override
    public CommonData getKeywordList(BasePageInfo basePageInfo, String keyword, String url) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketKeywordExample marketKeywordExample = new MarketKeywordExample();
        marketKeywordExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        MarketKeywordExample.Criteria criteria = marketKeywordExample.createCriteria();
        if (!StringUtil.isEmpty(keyword)) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        if (!StringUtil.isEmpty(url)) {
            criteria.andUrlLike("%" + url + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<MarketKeyword> marketKeywords = marketKeywordMapper.selectByExample(marketKeywordExample);
        PageInfo<MarketKeyword> marketKeywordPageInfo = new PageInfo<>(marketKeywords);
        return CommonData.data(marketKeywordPageInfo);
    }

    @Override
    @Transactional
    public MarketKeyword creatKeyword(MarketKeyword marketKeyword) {
        Date date = new Date();
        marketKeyword.setAddTime(date);
        marketKeyword.setUpdateTime(date);
        marketKeyword.setDeleted(false);
        marketKeywordMapper.insertSelective(marketKeyword);
        return marketKeyword;
    }

    @Override
    @Transactional
    public MarketKeyword updateKeyword(MarketKeyword marketKeyword) {
        marketKeyword.setUpdateTime(new Date());
        marketKeywordMapper.updateByPrimaryKeySelective(marketKeyword);
        MarketKeyword keyword = marketKeywordMapper.selectByPrimaryKey(marketKeyword.getId());
        return keyword;
    }

    @Override
    public void deleteKeyword(MarketKeyword marketKeyword) {
        marketKeyword.setDeleted(true);
        marketKeywordMapper.updateByPrimaryKeySelective(marketKeyword);
    }
}
